package com.core.netty.http.work;

import com.core.netty.util.NettyUtil;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class HttpMyReponse implements MyReponse {

    private String msg;

    private ChannelHandlerContext ctx;

    private boolean isSend = false;

    private Map<String, String> headerMap = new HashMap<>();

    public void setHeader(String name, String value) {
        headerMap.put(name, value);
    }

    @Override
    public void write(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return this.msg;
    }

    public void fullWrite(String message) {
        if (ctx != null) {
            if (message == null) {
                if (msg == null) {
                    message = "500,我不想说话";
                } else {
                    message = msg;
                }

            }
            try {
                FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, NettyUtil.getSendByteBuf(message));
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
                this.headerMap.forEach((k, v) -> {
                    response.headers().set(k, v);
                });
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
                this.isSend = true;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                fullWrite("500,I don't like speak!");
            }

        }
    }


    public ChannelHandlerContext getCtx() {
        return ctx;
    }

    public HttpMyReponse setCtx(ChannelHandlerContext ctx) {
        this.ctx = ctx;
        return this;
    }

    public boolean isSend() {
        return isSend;
    }

    public void setSend(boolean send) {
        isSend = send;
    }
}
